package com.thinkgem.jeesite.modules.house.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.google.zxing.oned.EAN13Reader;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.house.entity.Report;
import com.thinkgem.jeesite.modules.house.entity.Xiaoqu;
import com.thinkgem.jeesite.modules.house.service.ReportService;
import com.thinkgem.jeesite.modules.house.service.XiaoquService;
import com.thinkgem.jeesite.modules.oa.entity.Leave;
import com.thinkgem.jeesite.modules.oa.service.LeaveService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by Bing on 2016/12/19.
 */
@Controller
@RequestMapping(value = "${adminPath}/homelink")
public class XiaoquController extends BaseController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    protected XiaoquService xiaoquService;

    @Autowired
    protected ReportService reportService;

    @RequestMapping(value = {"region"})
    public String regionChengjiao(Xiaoqu xiaoqu, HttpServletRequest request, HttpServletResponse response, Model model) {
        try {
            String regionbname = request.getParameter("regionb");
            String regionsname = request.getParameter("regions");

            String title = "全北京";
            List<Report> list = null;
            if (StringUtils.isEmpty(regionbname) && StringUtils.isEmpty(regionsname)) {

                model.addAttribute("type", "regionb");
                model.addAttribute("regions", reportService.getRegionb());
                list = reportService.getAllData();
            }

            if (StringUtils.isNotBlank(regionbname)) {
                title = regionbname;
                model.addAttribute("type", "regions");
                model.addAttribute("regions", reportService.getRegions(regionbname));
                list = reportService.getByRegionb(regionbname);
            }

            if (StringUtils.isNotBlank(regionsname)) {
                title = regionsname;
                list = reportService.getByRegions(regionsname);
            }

            model.addAttribute("dataSource", generateReportJson(list, title));
            model.addAttribute("name", title);

        }catch (Exception e) {
            logger.info("查询大区 e: " + e.getMessage());
        }
        return "modules/homelink/region";
    }


    @RequestMapping(value = {"favorite"})
    public String list(Xiaoqu xiaoqu, HttpServletRequest request, HttpServletResponse response, Model model) {
        String xiaoquname = request.getParameter("xiaoquname");

        if (StringUtils.isNotBlank(xiaoquname)) {
            xiaoqu.setXiaoquname("%" + xiaoquname + "%");
        }

        Page<Xiaoqu> page = xiaoquService.find(new Page<Xiaoqu>(request, response), xiaoqu);
        model.addAttribute("page", page);
        return "modules/homelink/favorite";
    }

    @RequestMapping(value = {"detail"})
    public String report(HttpServletRequest request, HttpServletResponse response, Model model) {
        String xiaoqubianhao = request.getParameter("xiaoqubianhao");

//        if(StringUtils.isNotBlank(xiaoqubianhao)) {
//            xiaoqu.setXiaoquname("%"+xiaoquname+"%");
//        }

        Xiaoqu xiaoqu = xiaoquService.get(xiaoqubianhao);
        if (xiaoqu != null) {
            model.addAttribute("name", xiaoqu.getXiaoquname());
        }

        List<Report> list = reportService.getByXiaoquBianhao(xiaoqubianhao);
        model.addAttribute("list", list);
        model.addAttribute("dataSource", generateReportJson(list, xiaoqu.getXiaoquname()));
        return "modules/homelink/detail";
    }

    @RequestMapping(value = {"query"})
    public String query(HttpServletRequest request, HttpServletResponse response, Model model) {
        String xiaoquname = request.getParameter("xiaoquname");

//        if(StringUtils.isNotBlank(xiaoqubianhao)) {
//            xiaoqu.setXiaoquname("%"+xiaoquname+"%");
//        }

        List<Report> list = reportService.getByXiaoquName(xiaoquname);


        model.addAttribute("list", list);
        model.addAttribute("dataSource", generateReportJson(list, xiaoquname));
        model.addAttribute("name", xiaoquname);
        return "modules/homelink/detail";
    }

    @RequestMapping(value = {"regionb"})
    public String regionb(HttpServletRequest request, HttpServletResponse response, Model model) {

        try {
            //String regionbname = new String(request.getParameter("regionb").getBytes("iso-8859-1"),"utf-8");;
            String regionbname = request.getParameter("regionb");


            logger.info("查询大区: " + regionbname);
            List<Report> list = reportService.getByRegionb(regionbname);


            //model.addAttribute("list", list);
            model.addAttribute("dataSource", generateReportJson(list, regionbname));
            model.addAttribute("name", regionbname);
        }catch (Exception e) {
            logger.info("查询大区 e: " + e.getMessage());
        }

        return "modules/homelink/detail";
    }

    @RequestMapping(value = {"regions"})
    public String regions(HttpServletRequest request, HttpServletResponse response, Model model) {

        try {
            //String regionsName = new String(request.getParameter("regions").getBytes("iso-8859-1"),"utf-8");;
            String regionsName = request.getParameter("regions");

//        if(StringUtils.isNotBlank(xiaoqubianhao)) {
//            xiaoqu.setXiaoquname("%"+xiaoquname+"%");
//        }

            logger.info("查询区域: " + regionsName);
            List<Report> list = reportService.getByRegions(regionsName);


            //model.addAttribute("list", list);
            model.addAttribute("dataSource", generateReportJson(list, regionsName));
            model.addAttribute("name", regionsName);
        }catch (Exception e) {
            logger.info("查询大区 e: " + e.getMessage());
        }


        return "modules/homelink/detail";
    }

    private Object generateReportJson(List<Report> list, String xiaoquname) {
        //Map<String, Object> reportData = Maps.newHashMap();
        JSONObject reportData = new JSONObject();

        JSONArray cat = new JSONArray();
        JSONArray num = new JSONArray();
        JSONArray price = new JSONArray();
        Integer maxNum = 0, maxPrice = 0;
        for (Report report : list) {
            if (report.getNumber() > maxNum)
                maxNum = report.getNumber();
            if (report.getPrice() > maxPrice)
                maxPrice = report.getPrice();
            JSONObject catItem = new JSONObject();
            JSONObject numItem = new JSONObject();
            JSONObject priceItem = new JSONObject();
            catItem.put("label", report.getYear() + "-" + report.getMonth());
            cat.add(catItem);
            numItem.put("value", report.getNumber().toString());
            num.add(numItem);
            priceItem.put("value", report.getPrice().toString());
            price.add(priceItem);
        }

        JSONObject category = new JSONObject();
        //Map<String, Object> category = Maps.newHashMap();
        category.put("category", cat);
        JSONArray categories = new JSONArray();
        //List<Map> categories = new ArrayList<Map>();
        categories.add(category);
        reportData.put("categories", categories);


        JSONObject seriesNum = new JSONObject();
        seriesNum.put("data", num);

        JSONObject seriesPrice = new JSONObject();
        seriesPrice.put("renderAs", "line");
        seriesPrice.put("parentYAxis", "S");
        seriesPrice.put("data", price);

        JSONArray dataset = new JSONArray();
        //List<Map> dataset = new ArrayList<Map>();
        dataset.add(seriesNum);
        dataset.add(seriesPrice);
        reportData.put("dataset", dataset);

        JSONObject chart = new JSONObject();
        //Map<String, Object> chart = Maps.newHashMap();
        chart.put("caption", xiaoquname + " 成交报表");
        chart.put("subCaption", "历年按月成交量及平均单价");
        chart.put("captionFontSize", "14");
        chart.put("subcaptionFontSize", "14");
        chart.put("subcaptionFontBold", "0");
        chart.put("xAxisname", "Month");
        chart.put("pYAxisName", "Amount");
        chart.put("sYAxisName", "Unit Price");
        chart.put("YAxisMaxValue", maxNum*2);
        chart.put("sYAxisMaxValue", maxPrice.toString());
        chart.put("paletteColors", "#0075c2,#1aaf5d,#f2c500");
        chart.put("showAlternateHGridColor", "0");
        chart.put("showPlotBorder", "0");
        chart.put("usePlotGradientColor", "0");
        chart.put("baseFontColor", "#333333");
        chart.put("baseFont", "Helvetica Neue,Arial");
        chart.put("showBorder", "0");
        chart.put("bgColor", "#ffffff");
        chart.put("showShadow", "0");
        chart.put("canvasBgColor", "#ffffff");
        chart.put("showCanvasBorder", "0");
        chart.put("legendBorderAlpha", "0");
        chart.put("legendShadow", "0");
        chart.put("showValues", "1");
        chart.put("divlineAlpha", "100");
        chart.put("divlineColor", "#999999");
        chart.put("divlineThickness", "1");
        chart.put("divLineDashed", "1");
        chart.put("divLineDashLen", "1");
        chart.put("numVisiblePlot", "48");
        chart.put("exportEnabled", "1");
        chart.put("flatScrollBars", "1");
        chart.put("scrollheight", "10");

        reportData.put("chart", chart);

        return reportData;

    }
}
